package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Redis测试控制器
 */
@RestController
@RequestMapping("/api/redis-test")
@CrossOrigin
public class RedisTestController {
    
    @Autowired
    private RedisUtil redisUtil;
    
    /**
     * 测试Redis连接
     */
    @GetMapping("/connection")
    @RequirePermission("admin:monitor:system")
    public Result<Map<String, Object>> testConnection() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 测试基本操作
            String testKey = "redis_test_key";
            String testValue = "Redis连接测试成功！时间：" + System.currentTimeMillis();
            
            // 设置值
            boolean setResult = redisUtil.set(testKey, testValue, 60);
            
            // 获取值
            Object getValue = redisUtil.get(testKey);
            
            // 检查key是否存在
            boolean hasKey = redisUtil.hasKey(testKey);
            
            result.put("setResult", setResult);
            result.put("getValue", getValue);
            result.put("hasKey", hasKey);
            result.put("message", "Redis连接测试成功");
            result.put("redisInfo", redisUtil.getRedisInfo());
            
            // 清理测试数据
            redisUtil.del(testKey);
            
            return Result.success(result);
            
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("message", "Redis连接失败");
            errorResult.put("error", e.getMessage());
            return Result.error("Redis连接测试失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取Redis信息
     */
    @GetMapping("/info")
    @RequirePermission("admin:monitor:cache")
    public Result<Map<String, Object>> getRedisInfo() {
        try {
            Map<String, Object> info = redisUtil.getRedisInfo();
            return Result.success(info);
        } catch (Exception e) {
            return Result.error("获取Redis信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 清理Redis缓存
     */
    @PostMapping("/clear")
    @RequirePermission("admin:monitor:cache:clear")
    public Result<String> clearRedis() {
        try {
            redisUtil.flushAll();
            return Result.success("Redis缓存清理成功");
        } catch (Exception e) {
            return Result.error("Redis缓存清理失败：" + e.getMessage());
        }
    }
}
